<?php


namespace App\Http\Controllers\Api;


use App\Http\Controllers\Controller;
use App\Models\Classification;
use App\Models\Commodity;
use App\Models\CommodityOrder;
use App\Models\CommodityOrderDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class CommodityController extends Controller
{

    public function goodsClass(Request $request)
    {
        $data = Classification::get();
        return $this->makeResponse($data, '查询成功', 200);
    }

    public function goodsList(Request $request)
    {
        $classId = $request->input('class_id');
        $data = Commodity::where('class_id', $classId)->paginate(10);
        return $this->makeResponse($data, '查询成功', 200);

    }

    public function createOrder(Request $request)
    {
        $item = $request->input('item');
//        $contacts= $request->input('contacts');
        $mobile = $request->input('mobile');
        $address = $request->input('address');

        DB::beginTransaction();
        try {
            $sn = self::createSn();
            $order = [
                'internal_order_sn' => $sn,
                'order_status' => 1,
                'contacts' => '',
                'mobile' => $mobile,
                'full_address' => $address
            ];
            $orderId = CommodityOrder::insertGetId($order);
            $orderDetails = [];
            $totalPrice = 0;
            foreach ($item as $v) {
                $commodity = Commodity::find($v['id']);

                $orderDetails[] = [
                    'spu_id' => $commodity->id,
                    'spu_name' => $commodity->name,
                    'number' => $v['num'],
                    'original_price' => $commodity->price,
                    'order_id' => $orderId,
                    'total_price' => $commodity->price * $v['num'],
                ];
                $totalPrice += $commodity->price * $v['num'];
            }
            CommodityOrderDetail::insert($orderDetails);
            CommodityOrder::where('id', $orderId)->update(['order_total_price' => $totalPrice]);
            DB::commit();
            return makeResponse([], '提交成功', 200);
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->makeResponse([], $exception->getMessage() . ' [LINE]:' . $exception->getLine(), 500);
        }
    }

}